package com.lixin.web.netty.handler;

import com.lixin.web.netty.NettyServerStarter;
import com.lixin.web.netty.NettyUtil;
import com.lixin.web.netty.UserSessionManager;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Description:
 * Copyright:   Copyright (c)2023
 * Company:     sci
 *
 * @author: 张李鑫
 * @version: 1.0
 * Create at:   2023-07-29 19:01:53
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2023-07-29     张李鑫                     1.0         1.0 Version
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class UserManagementHandler extends ChannelDuplexHandler {

    @Autowired
    private UserSessionManager userSessionManager;

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent idleStateEvent) {
            IdleState state = idleStateEvent.state();
            if (state == IdleState.READER_IDLE || state == IdleState.WRITER_IDLE) {
                ctx.close();
                return;
            }
        }
        super.userEventTriggered(ctx, evt);
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        Integer userId = NettyUtil.getAttr(channel, NettyUtil.UID);
        log.info("channelInactive ...... userId:{}", userId);
        userSessionManager.removeUserSession(userId);
        NettyServerStarter.ctxThreadLocal.remove();
    }
}
